package com.androidme.app.examples;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import com.androidme.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class TestApkUpdateActivity extends Activity {
    ProgressDialog pd;
    int fileSize;
    int downLoadFileSize;
    private Handler mProgressHandler = new Handler();
    String filename;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (!Thread.currentThread().isInterrupted()) {
                switch (msg.what) {
                    case 0:
                        pd.setMax(fileSize);
                    case 1:
                        pd.setProgress(downLoadFileSize);
                        break;
                    case 2:
                        Toast.makeText(TestApkUpdateActivity.this, "文件下载完成", 1).show();
                        break;
                    case -1:
                        String error = msg.getData().getString("error");
                        Toast.makeText(TestApkUpdateActivity.this, error, 1).show();
                        break;
                }
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.testupdate);
        pd = new ProgressDialog(TestApkUpdateActivity.this);
        pd.setMessage("updating");
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.show();
        new Thread() {
            public void run() {
                try {
                    down_file("http://t.corp.snda.com/st/download/ip.apk", Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator);
                    update();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public void down_file(String url, String path) throws IOException {
        filename = url.substring(url.lastIndexOf("/") + 1);
        URL myURL = new URL(url);
        URLConnection conn = myURL.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        this.fileSize = conn.getContentLength();
        if (this.fileSize <= 0) throw new RuntimeException("无法获知文件大小 ");
        if (is == null) throw new RuntimeException("stream is null");
        FileOutputStream fos = new FileOutputStream(path + filename);
        byte buf[] = new byte[1024];
        downLoadFileSize = 0;
        sendMsg(0);
        do {
            int numread = is.read(buf);
            if (numread == -1) {
                break;
            }
            fos.write(buf, 0, numread);
            downLoadFileSize += numread;

            sendMsg(1);
        } while (true);
        sendMsg(2);
        try {
            is.close();
        } catch (Exception ex) {
            Log.e("tag", "error: " + ex.getMessage(), ex);
        }
    }

    private void sendMsg(int flag) {
        Message msg = new Message();
        msg.what = flag;
        handler.sendMessage(msg);
    }

    private void update() {
        mProgressHandler.post(new Runnable() {
            public void run() {
                pd.cancel();
                install();
                finish();
            }
        });
    }

    private void install() {
        Intent i = new Intent();
        i.setAction(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "ip.apk")), "application/vnd.android.package-archive");
        startActivity(i);
    }
}
